
/**
 * @file key_sn.c
 * @brief 读写移为专用的SN相关接口
 * @attention 应用非必须只用读取接口，此和客户SN有所区分
 * @author  ()
 * @version 1.0
 * @date 2024-11-04
 * @ingroup flash
 * @copyright Copyright (C) 2019 Queclink Wireless Solutions (ShenZhen) Co., Ltd. All Rights Reserved.
 *
 * @par 修改日志:
 * <table>
 * <tr><th>Date       <th>Version <th>Author  <th>Description
 * <tr><td>2024-11-04 <td>1.0     <td>     <td>内容
 * </table>
 */
#include <stdint.h>
#include <stdio.h>
#include <string.h>

#include "global.h"

#define LOG_TAG "PARM"
#include "easylog/elog.h"

#include "key_params.h"
#include "../protocol_params/protocol_params.h"


#include <stdint.h>
#include <stdint.h>

/**
 * @brief sn关键参数结构体
 */
typedef struct
{
    uint8_t len;
    char sn[SN_MAX_SIZE];
    uint8_t checksum;
} sn_key_params_t;

#include "utils/utils_checksum.h"

/**
 * @brief	   加载SN备份参数，仅在参数掉了以后才会调用这个函数
 * @return 	   执行结果，0表示成功，非0表示失败
 * @attention 如果首扇区未存储,并不保证能加载成功
 **/
int32_t load_quec_sn(char *sn, ssize_t len)
{
    sn_key_params_t key;
    char temp[256] = {0};
    uint8_t checksum = 0;

    /**
     * @brief 从第一分区读取SN信息
     */
    memset(&key, 0, sizeof(key));
    if (!load_key_params(DIRECT_SN_OFFSET, (unsigned char *)&temp, sizeof(temp), -1)) {
        log_e("load key_param_sn failed, read fail\r\n");
        return ECONFIG;
    }

    key.len = temp[0];
    if(key.len >= sizeof(key.sn)) {
        log_e("load key_param_sn failed, read fail: %d\r\n", key.len);
        return ECONFIG;
    }

    memcpy(key.sn, temp + 1, key.len);
    key.checksum = temp[key.len + 1];
    checksum = utils_calucate_checksum((uint8_t *)&key.sn, key.len);
    if ((key.checksum & checksum) != 0) {
        log_e("load key_param_sn failed, checksum faild\r\n");
        return ECONFIG;
    }
   
    snprintf(sn, len, "%s", key.sn);

    return SUCC;
}

/**
 * @brief 保存移为SN
 * @param  sn               My Param doc
 * @param  sn_len           My Param doc
 * @return int32_t 0 - succ | other - failed
 */
int32_t save_quec_sn(char *sn)
{
    sn_key_params_t key;

    memset(&key, 0, sizeof(key));
    key.len = strlen(sn);
    memcpy(key.sn, (char *)sn, strlen(sn));

    save_key_params(DIRECT_SN_OFFSET, (unsigned char *)&key, sizeof(key),
                    -1);
    return 0;
}
